# 在图片中选取roi并用鼠标画出矩形框
import cv2
import numpy as np

img = cv2.imread("data/image/seeding00374.jpg")
h, w ,d = img.shape
drawing = False
ix, iy = -1, -1
tempFlag = False
GSD = 1.37  # cm/p
area = 0  # 单位m^2
p = np.array([0, 0, 0, 0])
rectangle_color = (0, 0, 255)


def draw_circle(event, x, y, flags, param):
    global ix, iy, drawing, mode, cap, template, tempFlag, area
    if event == cv2.EVENT_LBUTTONDOWN:
        tempFlag = True
        drawing = True
        # ix, iy = x, y  # 按下鼠标左键，用全局变量ix,iy记录下当前坐标点
        p[0:2] = x, y
    elif event == cv2.EVENT_LBUTTONUP:
        if drawing == True:
            drawing = False  # 鼠标左键抬起，画出矩形框
            p[2:4] = x, y
            cv2.rectangle(img, (p[0], p[1]), (p[2], p[3]), rectangle_color, 1)
            # template = img[iy:y, ix:x, :]  #截取框中的目标图像
            area = get_area(p)
            density = count_seed(p)
            label = "%.2f" % density
            plot_label(p, img, label)
            print(ix, iy, x, y, 'area=%g, GSD=%g, density=%g' % (area, GSD, density))
            # cap = cv2.VideoCapture(-1)       #打开摄像头
            cv2.imshow('density_calculator', img)  # 显示画框后的图像
            # cv2.imshow('template',template)


def plot_label(x, img, label, thickness=2, color=(0, 0, 255)):
    tl = thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1
    tf = max(tl - 1, 1)
    t_size = cv2.getTextSize(label, 0, fontScale=tl / 6, thickness=tf)[0]
    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
    c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
    cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled
    cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 6, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)


def get_area(p):
    return abs(p[0] - p[2]) * abs(p[1] - p[3]) * GSD * GSD * 0.0001


def count_seed(pt, txt=''):
    x, y, x1, y1 = pt
    cnt = 0
    f = open('data/txt/seeding00374.txt', 'r')
    lines = f.readlines()
    for line in lines:
        line = line.strip().split(' ')
        xb, yb = line[1:3]
        xb = int(float(xb)*w)
        yb = int(float(yb)*h)
        cv2.circle(img, (xb, yb), 1, (0, 255, 0), 4)
        if x < xb < x1 and y < yb < y1:
            cnt += 1
    return cnt / get_area(pt)


cv2.namedWindow("density_calculator")
cv2.setMouseCallback("density_calculator", draw_circle)
cv2.imshow("density_calculator", img)

while (True):
    try:
        cv2.waitKey(100)
    except Exception:
        cv2.destroyAllWindows()
        break

cv2.waitKey(0)
cv2.destroyAllWindows()
